package com.sskj.xgja.mine;

import android.app.Activity;
import android.app.AlertDialog;
import android.arch.lifecycle.Observer;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gyf.barlibrary.ImmersionBar;
import com.hjq.toast.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.base.BuildConfig;
import com.sskj.base.data.User;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.MobileUtil;
import com.sskj.base.utils.SPUtils;
import com.sskj.xgja.AppManager;
import com.sskj.xgja.LiveDataBus;
import com.sskj.xgja.MVPFragment;
import com.sskj.xgja.MyApplication;
import com.sskj.xgja.R;
import com.sskj.xgja.api.Api;
import com.sskj.xgja.login.LoginActivity;
import com.sskj.xgja.util.TipUtilLogin;
import com.sskj.xgja.verify.IntroductionActivity;
import com.sskj.xgja.verify.Verify4Activity;
import com.sskj.xgja.view.SelectPictureDialog;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @author Hey
 * Create at  2019/03/20
 */
public class MineFragment extends MVPFragment<MinePresenter> {

    @BindView(R.id.user_head)
    CircleImageView userHead;
    @BindView(R.id.user_mobile)
    TextView userMobile;

    @BindView(R.id.llRecharge)
    LinearLayout llRecharge;
    @BindView(R.id.llWithdraw)
    LinearLayout llWithdraw;
    @BindView(R.id.go_verify)
    TextView goVerify;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.verifyLayout)
    LinearLayout verifyLayout;
    @BindView(R.id.accountLayout)
    LinearLayout accountLayout;
    @BindView(R.id.depositLayout)
    LinearLayout depositLayout;
    @BindView(R.id.withdrawLayout)
    LinearLayout withdrawLayout;
    @BindView(R.id.guideLayout)
    LinearLayout guideLayout;
    @BindView(R.id.settingLayout)
    LinearLayout settingLayout;
    @BindView(R.id.detailLayout)
    LinearLayout detailLayout;
    @BindView(R.id.logout)
    TextView logout;
    @BindView(R.id.tvMoney)
    TextView tvMoney;
    @BindView(R.id.ivSee)
    ImageView ivSee;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    private SelectPictureDialog selectPictureDialog;

    private final int SELECT_PICTURE = 1000;

    private User userData;

    private String path;
    private String money;
    private boolean isSee = true;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void initView() {
        initRefreshLayout(smartRefreshLayout);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mPresenter.getAccountDetail(getAccount(), true);
            }
        });
        ClickUtil.click(logout, view -> {
            AlertDialog dialog = new AlertDialog.Builder(getContext())
                    .setMessage("确定要退出吗?")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            MyApplication.token = null;
                            MyApplication.account = null;
                            SPUtils.clear(getContext(), "");
                            LoginActivity.start(getContext());
                            AppManager.getInstance().finish2Login();
                            if (Api.getInstance() != null) {
                                Api.setInstance();
                            }
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();

        });
//        ClickUtil.click(llRecharge, view -> {  // 入金
//            RechargeActivity.start(getContext());
//        });
        LiveDataBus.get().with(1, User.class)
                .observe(MyApplication.instance, user -> {
                    if (user != null) {
                        userData = user;
                        if (userMobile == null)
                            return;
                        userMobile.setText(MobileUtil.hideMobile(user.getMobile()));
                        logout.setVisibility(View.VISIBLE);
                        if (user.getHeadImgUrl() != null) {
                            Glide.with(getContext()).load(BuildConfig.BASE_URL + user.getHeadImgUrl()).into(userHead);
                        }
                        userName.setText(TextUtils.isEmpty(user.getRealname()) ? "----" : user.getRealname());
                        if (userData.getAuthStatus().equals("1")) {  //1 未认证 2 待审核 3 已通过  4拒绝
                            goVerify.setText("去认证>");

                            ClickUtil.click(llRecharge, view -> ToastUtils.show("请先进行账户认证"));
                            ClickUtil.click(llWithdraw, view -> ToastUtils.show("请先进行账户认证"));
                            return;
                        }
                        if (userData.getAuthStatus().equals("2")) {
                            goVerify.setText("审核中>");
                            ClickUtil.click(llRecharge, view -> ToastUtils.show("账户认证审核中，请耐心等待"));
                            ClickUtil.click(llWithdraw, view -> ToastUtils.show("账户认证审核中，请耐心等待"));
                            return;
                        }

                        if (userData.getAuthStatus().equals("3")) {
                            goVerify.setText("已通过>");
                            ClickUtil.click(llRecharge, view -> {  // 入金
                                RechargeActivity.start(getContext());
                            });
                            ClickUtil.click(llWithdraw, view -> {
                                if (!userData.getIsQd().equals("1")) {
                                    ToastUtils.show("请先设置资金密码");
                                    return;
                                }
                                CashOutActivity.start(getContext());
                            });
                            return;
                        }
                        if (userData.getAuthStatus().equals("4")) {
                            goVerify.setText("已拒绝>");
                            ClickUtil.click(llRecharge, view -> ToastUtils.show("请先进行账户认证"));
                            ClickUtil.click(llWithdraw, view -> ToastUtils.show("请先进行账户认证"));
                            return;
                        }
                    } else {
                        userMobile.setText("请登录");
                        logout.setVisibility(View.GONE);
                        ClickUtil.click(llRecharge, view -> TipUtilLogin.loginDialog(getContext()));
                        ClickUtil.click(llWithdraw, view -> TipUtilLogin.loginDialog(getContext()));
                    }
                });
//        userViewModel.getUser(getContext()).observe(this, new Observer<User>() {
//            @Override
//            public void onChanged(@Nullable User user) {
//                if (user != null) {
//                    userData = user;
//                    userMobile.setText(MobileUtil.hideMobile(user.getMobile()));
//                    logout.setVisibility(View.VISIBLE);
//                    if (user.getHeadImgUrl() != null) {
//                        Glide.with(getContext()).load(BuildConfig.BASE_URL + user.getHeadImgUrl()).into(userHead);
//                    }
//                    userName.setText(TextUtils.isEmpty(user.getRealname()) ? "----" : user.getRealname());
//                    if (userData.getAuthStatus().equals("1")) {  //1 未认证 2 待审核 3 已通过  4拒绝
//                        goVerify.setText("去认证>");
//                        ClickUtil.click(llRecharge, view -> ToastUtils.show("请先进行账户认证"));
//                        ClickUtil.click(llWithdraw, view -> ToastUtils.show("请先进行账户认证"));
//                        return;
//                    }
//                    if (userData.getAuthStatus().equals("2")) {
//                        goVerify.setText("审核中>");
//                        ClickUtil.click(llRecharge, view -> ToastUtils.show("账户认证审核中，请耐心等待"));
//                        ClickUtil.click(llWithdraw, view -> ToastUtils.show("账户认证审核中，请耐心等待"));
//                        return;
//                    }
//                    if (userData.getAuthStatus().equals("3")) {
//                        goVerify.setText("已通过>");
//                        ClickUtil.click(llRecharge, view -> {  // 入金
//                            RechargeActivity.start(getContext());
//                        });
//                        ClickUtil.click(llWithdraw, view -> {
//                            CashOutActivity.start(getContext());
//                        });
//                        return;
//                    }
//                    if (userData.getAuthStatus().equals("4")) {
//                        goVerify.setText("已拒绝>");
//                        ClickUtil.click(llRecharge, view -> ToastUtils.show("请先进行账户认证"));
//                        ClickUtil.click(llWithdraw, view -> ToastUtils.show("请先进行账户认证"));
//                        return;
//                    }
//                } else {
//                    userMobile.setText("请登录");
//                    logout.setVisibility(View.GONE);
//                    ClickUtil.click(llRecharge, view -> TipUtilLogin.loginDialog(getContext()));
//                    ClickUtil.click(llWithdraw, view -> TipUtilLogin.loginDialog(getContext()));
//                }
//            }
//        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
            mPresenter.getAccountDetail(getAccount(), true);
        } else {
            userMobile.setText("请登录");
            logout.setVisibility(View.GONE);
            ClickUtil.click(llRecharge, view -> TipUtilLogin.loginDialog(getContext()));
            ClickUtil.click(llWithdraw, view -> TipUtilLogin.loginDialog(getContext()));
        }
    }

    @Override
    public void initData() {
        ClickUtil.click(userHead, view -> {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                uploadHead();
            } else {
                TipUtilLogin.loginDialog(getContext());
            }
        });

        //实名认证
        verifyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userData != null && !TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                    if (userData.getAuthStatus().equals("1")) {
                        IntroductionActivity.start(getContext());
                        return;
                    }
                    if (userData.getAuthStatus().equals("2")) {
                        Verify4Activity.start(getContext());
                        return;
                    }
                    if (userData.getAuthStatus().equals("3")) {
                        ToastUtils.show("认证已通过");
                        return;
                    }
                    if (userData.getAuthStatus().equals("4")) {
                        Verify4Activity.start(getContext());
                        return;
                    }

                } else {
                    TipUtilLogin.loginDialog(getContext());
                }
            }
        });
        //账单明细
        ClickUtil.click(accountLayout, view -> {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                AccountDetailActivity.start(getContext());
            } else {
                TipUtilLogin.loginDialog(getContext());
            }
        });
        ClickUtil.click(detailLayout, (v) -> {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                DetailActivity.start(getContext());
            } else {
                TipUtilLogin.loginDialog(getContext());
            }
        });
        //入金查询
        ClickUtil.click(depositLayout, view -> {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                AssetRecordActivity.start(getContext(), AssetRecordActivity.Recharge);
            } else {
                TipUtilLogin.loginDialog(getContext());
            }
        });
        //出金查询
        ClickUtil.click(withdrawLayout, view -> {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                AssetRecordActivity.start(getContext(), AssetRecordActivity.WithDraw);
            } else {
                TipUtilLogin.loginDialog(getContext());
            }
        });
        //新手指导
        ClickUtil.click(guideLayout, view -> GuideActivity.start(getContext()));
        //设置
        ClickUtil.click(settingLayout, view -> SettingActivity.start(getContext()));

    }

    public void uploadHead() {
        userHead.setOnClickListener(v -> {
            if (selectPictureDialog == null) {
                selectPictureDialog = new SelectPictureDialog(getContext());
                selectPictureDialog.setOnSelectListener(new SelectPictureDialog.SelectListener() {
                    @Override
                    public void selectByAlbum() {
                        PictureSelector.create(MineFragment.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .compress(true)
                                .minimumCompressSize(100)
                                .forResult(SELECT_PICTURE);
                    }

                    @Override
                    public void selectByPhoto() {
                        PictureSelector.create(MineFragment.this)
                                .openCamera(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .compress(true)
                                .minimumCompressSize(100)
                                .forResult(SELECT_PICTURE);
                    }
                });
            }
            selectPictureDialog.show();
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (!TextUtils.isEmpty(MyApplication.getAccount()) && !TextUtils.isEmpty(MyApplication.getToken())) {
                mPresenter.getAccountDetail(getAccount(), true);
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(0);
                    if (media.isCompressed()) {
                        path = media.getCompressPath();
                    } else {
                        path = media.getPath();
                    }
                    mPresenter.uploadImage(new File(path));
                }
            }
        }
    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    public void uploadSuccess(String data) {
        Glide.with(this).load(path).into(userHead);
    }

    public void setAccountInfo(User data) {
        money = data.getWallone();
        tvMoney.setText(money);
        ClickUtil.click(100, ivSee, (v) -> {
            if (isSee) {
                isSee = false;
                ivSee.setImageResource(R.mipmap.icon_lock);
                tvMoney.setText("****");
            } else {
                isSee = true;
                ivSee.setImageResource(R.mipmap.icon_unlock);
                tvMoney.setText(money);
            }
        });
        LiveDataBus.get().with(1, User.class).postValue(data);
//        userViewModel.setUser(getContext(), data);
        userMobile.setText(MobileUtil.hideMobile(data.getMobile()));
        logout.setVisibility(View.VISIBLE);
        if (data.getHeadImgUrl() != null) {
            Glide.with(getContext()).load(BuildConfig.BASE_URL + data.getHeadImgUrl()).into(userHead);
        }
        userName.setText(TextUtils.isEmpty(data.getRealname()) ? "----" : data.getRealname());
        switch (data.getAuthStatus()) {  //1 未认证 2 待审核 3 已通过  4拒绝
            //通过
            case "3":
                goVerify.setText("已通过>");
                ClickUtil.click(llRecharge, view -> {
                    RechargeActivity.start(getContext());
                });
                ClickUtil.click(llWithdraw, view -> {
                    CashOutActivity.start(getContext());
                });
                break;
            //待审核
            case "2":
                goVerify.setText("审核中>");
                ClickUtil.click(llRecharge, view -> ToastUtils.show("账户认证审核中，请耐心等待"));
                ClickUtil.click(llWithdraw, view -> ToastUtils.show("账户认证审核中，请耐心等待"));
                break;
            //拒绝
            case "4":
                goVerify.setText("已拒绝>");
                ClickUtil.click(llRecharge, view -> ToastUtils.show("请先进行账户认证"));
                ClickUtil.click(llWithdraw, view -> ToastUtils.show("请先进行账户认证"));
                break;
            //未认证
            case "1":
                goVerify.setText("去认证>");
                ClickUtil.click(llRecharge, view -> ToastUtils.show("请先进行账户认证"));
                ClickUtil.click(llWithdraw, view -> ToastUtils.show("请先进行账户认证"));
                break;
        }
    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }

    @Override
    public boolean immersionBarEnabled() {
        return true;
    }

    public void finishRefresh() {
        smartRefreshLayout.finishRefresh();
    }
}
